package com.action;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.bean.PersonBean;
import com.service.UserService;

public class CommonAction extends DispatchAction {
	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		request.getSession().invalidate();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		WebApplicationContext wctx = WebApplicationContextUtils.getWebApplicationContext(this.getServlet().getServletContext());
		UserService service = (UserService) wctx.getBean("userTarget");
		if(!service.hasMatchUser(username, password)){
			request.setAttribute("error", "用户名或密码错误！");
			return mapping.findForward("error");
		}
		PersonBean bean = service.findUserByEname(username);
		request.getSession().setAttribute("person", bean);
		request.getSession().setAttribute("isLogin", "true");
		int ret = service.loginSuccess(username);
		if(ret == 0){
			request.setAttribute("error", "系统内部错误！");
		}
		return mapping.findForward("loginSuccess");
	}
	
	public ActionForward logout(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			request.getSession().invalidate();
			return mapping.findForward("logout");
		} catch(Exception e) {
			return mapping.findForward("logout");
		}
	}
}
